<template>
  <div>
     <div class="register_con">
    <div class="l_con fl">
        <a class="reg_logo"><img src="/static/images/logo.png"></a>
        <div class="reg_slogan">商品美 · 种类多 · 欢迎光临</div>
        <div class="reg_banner"></div>
    </div>

    <div class="r_con fr">
        <div class="reg_title clearfix">
            <h1>用户注册</h1>
            <a href="/login.html">登录</a>
        </div>
        <div class="reg_form clearfix" id="app" v-cloak>
            <form>
                <ul>
                    <li>
                        <label>用户名:</label>
                        <input type="text" v-model="username" @blur="check_username" name="user_name" id="user_name">
                        <span v-show="error_name" class="error_tip">{{error_name_message}}</span>
                    </li>
                    <li>
                        <label>密码:</label>
                        <input type="password" v-model="password" @blur="check_pwd" name="pwd" id="pwd">
                        <span v-show="error_password" class="error_tip">密码最少8位，最长20位</span>
                    </li>
                    <li>
                        <label>确认密码:</label>
                        <input type="password" v-model="password2" @blur="check_cpwd" name="cpwd" id="cpwd">
                        <span v-show="error_check_password" class="error_tip">两次输入的密码不一致</span>
                    </li>
                    <li>
                        <label>手机号:</label>
                        <input type="text" name="phone" v-model="mobile" @blur="check_phone" id="phone">
                        <span v-show="error_phone" class="error_tip">{{error_phone_message}}</span>
                    </li>
                    <li>
                        <label>图片验证码:</label>
                        <input type="text" v-model="image_code" @blur="check_image_code" style="width:172px; height:40px">
                        <img :src="image_url" @click="generate_image_code" style="margin-left: 3px;width: 108px;height: 40px;"/>
                        <span v-show="error_image_code" class="error_tip">请输入图形验证码</span>
                    </li>
                    <li>
                        <label>短信验证码:</label>
                        <input type="text" v-model="sms_code" @blur="check_sms_code" name="msg_code" id="msg_code" class="msg_input">
                        <a href="javascript:;" @click="send_sms_code" class="get_msg_code">{{ sms_code_tip }}</a>
                        <span v-show="error_sms_code" class="error_tip">{{ sms_code_error_tip }}</span>
                    </li>
                    <li class="agreement">
                        <input type="checkbox" v-model="allow" @change="check_allow" name="allow" id="allow" checked="checked">
                        <label>同意”美多商城用户使用协议“</label>
                        <span v-show="error_allow" class="error_tip2">alert</span>
                    </li>
                    <li class="reg_sub">
                        <input value="注 册" name="" @click="on_submit">
                    </li>
                </ul>
            </form>
        </div>

    </div>

</div>

<div class="footer no-mp">
    <div class="foot_link">
        <a href="#">关于我们</a>
        <span>|</span>
        <a href="#">联系我们</a>
        <span>|</span>
        <a href="#">招聘人才</a>
        <span>|</span>
        <a href="#">友情链接</a>
    </div>
    <p>CopyRight © 2016 北京美多商业股份有限公司 All Rights Reserved</p>
    <p>电话：010-****888 京ICP备*******8号</p>
</div> 
  </div>
</template>

<script>
import axios from "axios"
export default {
    data() {
        return {

            error_name: false,
            error_password: false,
            error_check_password: false,
            error_phone: false,
            error_allow: false,
            error_sms_code: false,
            error_image_code:false,

            username: '',
            password: '',
            password2: '',
            mobile: '',
            image_code:'',
            sms_code: '',
            allow: true,

            send_flag: false,
            sms_code_tip: '获取短信验证码',
            sms_code_error_tip: '短信验证码错误',
            error_name_message:'',
            error_phone_message:'',
            host: host,
            image_url:'',   // 图片地址
        }
    },
     mounted() {
        this.generate_image_code();
    },
    methods: {
        generate_image_code(){
            this.uuid = this.generate_uuid()
            this.image_url = this.host + '/image_codes/' + this.uuid + '/'
            // this.image_url = "http://localhost:8080/static/images/logo.png"
        },
        check_image_code(){
            var len = this.image_code.length;
            if(len != 4){
                this.error_image_code = true;
            }else{
                this.error_image_code = false;
            }
        },
        check_username() {
      var len = this.username.length;
      if (len < 5 || len > 20) {
        this.error_name_message = '请输入5-20个字符的用户'
        this.error_name = true;
      } else {
        this.error_name_message = ''
        this.error_name = false;
      }

      // 检查重名
      if (this.error_name == false) {
        // /usernames/xuyan/count/
        // /usernames/(?P<username>[a-zA-Z0-9_-]{5,20})/count/
        axios.get(this.host + '/usernames/' + this.username + '/count/', {
          responseType: 'json'
        })
          .then(response => {
            if (response.data.count > 0) {
              this.error_name_message = '用户名已存在';
              this.error_name = true;
            } else {
              this.error_name = false;
            }
          })
          .catch(error => {
            console.log(error.response.data);
          })
      }
    },
        check_pwd() {
            var len = this.password.length;
            if (len < 8 || len > 20) {
                this.error_password = true;
            } else {
                this.error_password = false;
            }
        },
        check_cpwd() {
            if (this.password != this.password2) {
                this.error_check_password = true;
            } else {
                this.error_check_password = false;
            }
        },
        check_phone() {
      var re = /^1[345789]\d{9}$/;
      if (re.test(this.mobile)) {
        this.error_phone_message = '您输入的手机号格式不正确'
        this.error_phone = false;
      } else {
        this.error_phone_message = ''
        this.error_phone = true;
      }

      if (this.error_phone == false) {
        axios.get(this.host + '/mobiles/' + this.mobile + '/count/', {
          responseType: 'json'
        })
          .then(response => {
            if (response.data.count > 0) {
              this.error_phone_message = '手机号已存在';
              this.error_phone = true;
            } else {
              this.error_phone = false;
            }
          })
          .catch(error => {
            console.log(error.response.data);
          })
      }
    },
        check_sms_code() {
            if (!this.sms_code) {
                this.error_sms_code = true;
            } else {
                this.error_sms_code = false;
            }
        },
        check_allow() {
            if (!this.allow) {
                this.error_allow = true;
            } else {
                this.error_allow = false;
            }
        },
        // 注册
        on_submit() {
            // debugger
            this.check_username();
            this.check_pwd();
            this.check_cpwd();
            this.check_phone();
            this.check_sms_code();
            this.check_allow();

            if (this.error_name == false &&
                this.error_password == false &&
                this.error_check_password == false &&
                this.error_phone == false &&
                this.error_sms_code == false &&
                this.error_allow == false
                ) {
                axios.post(this.host + '/register/', {
                    username: this.username,
                    password: this.password,
                    password2: this.password2,
                    mobile: this.mobile,
                    sms_code: this.sms_code,
                    allow: this.allow
                }, {
                    responseType: 'json'
                })
                    .then(response => {
                        if(response.data.code==0){
                            // 记录用户的登录状态
                            sessionStorage.clear();
                            localStorage.clear();
                            localStorage.token = response.data.token;
                            localStorage.username = response.data.username;
                            localStorage.user_id = response.data.id;
                            // this.$router.push('/index')
                        }else{
                            alert(response.data.msg)
                        }
                        
                    })
                    .catch(error => {
                        if (error.response.status == 400) {
                            if ('non_field_errors' in error.response.data) {
                                this.error_sms_code_message = error.response.data.non_field_errors[0];
                            } else {
                                this.error_sms_code_message = '数据有误';
                            }
                            this.error_sms_code = true;
                        } else {
                            console.log(error.response.data);
                        }
                    })
            }
        },
        // 生成uuid
        generate_uuid() {
            var d = new Date().getTime();
            if (window.performance && typeof window.performance.now === "function") {
                d += performance.now(); //use high-precision timer if available
            }
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        },
        //发送短信验证码
        send_sms_code() {
            if (this.send_flag == true) {
                return;
            }
            this.send_flag = true;

            this.check_phone();

            if (this.error_phone) {
                this.send_flag = false;
                return;
            }
             // /sms_code/13312341234/?image_code=xxxx&uuid=xxxx-xxxxx-xxxxxx
            axios.get(this.host + '/sms_codes/' + this.mobile + '/' + '?image_code='+this.image_code + '&uuid='+this.uuid)
                .then(response => {
                    var num = 60;
                    // debugger
                    var t = setInterval(()=> {
                        if (num == 1) {
                            clearInterval(t);
                            this.sms_code_tip = '获取短信验证码';
                            this.send_flag = false;
                        } else {
                            num -= 1;
                            this.sms_code_tip = '再过 ' + num + ' 秒后发送';
                        }
                    }, 1000);
                })
                .catch(error => {
                    this.send_flag = false;
					console.log(error.response.data);
                });
        }
    }

}
</script>

<style>

</style>